package com.micromall.service.impl;

import com.micromall.common.exception.BusiException;
import com.micromall.common.utils.Dict;
import com.micromall.common.utils.StringUtils;
import com.micromall.model.MiMember;
import com.micromall.mapper.MiMemberMapper;
import com.micromall.model.SysUser;
import com.micromall.service.IMiMemberService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.micromall.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Dante Fung
 * @since 2017-07-26
 */
@Service
public class MiMemberServiceImpl extends ServiceImpl<MiMemberMapper, MiMember> implements IMiMemberService {

    private static final Logger logger = LoggerFactory.getLogger(MiMemberServiceImpl.class);

    @Autowired
    private ISysUserService sysUserService;

    public String hadExistAutoRegister(String phoneNo, String receiverName){
        // 判断用户是否已经注册过.
        MiMember mimemberQuery = new MiMember();
        mimemberQuery.setMemberNo("WS"+phoneNo);
        MiMember miMember = selectById(mimemberQuery);
        if (null == miMember) {
            // 注册会员表
            MiMember miMemberInsert = new MiMember();
            miMemberInsert.setMemberNo("WS"+phoneNo);
            miMemberInsert.setPhone(phoneNo);
            miMemberInsert.setCreateTime(new Date());// 非空约束
            miMemberInsert.setCardType("0");// 待审核会员
            miMemberInsert.setAgentNo("system");// 非空约束
            miMemberInsert.setCreateNo("system");// 非空约束
            miMemberInsert.setCompanyCode("CN");
            miMemberInsert.setLocked("0");// 正常授权  非空约束
            miMemberInsert.setRoleId("1");// 非空约束
            miMemberInsert.setIdNo("system");// 非空约束
            miMemberInsert.setLastName(receiverName);
            boolean flag = insert(miMemberInsert);
            // 用户表也要注册
            SysUser user = new SysUser();
            user.setUserCode("SW"+phoneNo);
            user.setPassword("123456");
            user.setUserName(StringUtils.isNotBlank(receiverName)?receiverName:"sysgen");
            user.setCompanyCode("CN");
            user.setUserType("A");
            user.setDefCharacterCoding("ZH");
            user.setState("1");
            sysUserService.insert(user);
            if (!flag) {
                if (logger.isDebugEnabled()) {
                    logger.info("[用户自动注册失败!]");
                }
                return Dict.Sys_User.RegisterStatusCode.AUTO_REGISTER_FAIL.getCode();
            } else {
                return Dict.Sys_User.RegisterStatusCode.AUTO_REGISTER_SUCCESS.getCode();
            }
        } else {
            logger.info("用户已经注册!");
            return Dict.Sys_User.RegisterStatusCode.HAD_EXIST.getCode();
        }
    }


}
